package cn.com.test.common.mysql;

import javax.servlet.ServletConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

@WebServlet(name = "mysqlServlet", urlPatterns = {"/web/selectUserName"}, loadOnStartup = -1)
public class MysqlServlet extends HttpServlet {

	private Connection con;

	@Override
	public void init(ServletConfig config) {
		try {
			Class.forName("com.mysql.cj.jdbc.Driver");
			con = DriverManager.getConnection("jdbc:mysql://localhost:3306/edaily?serverTimezone=UTC&useSSL=false",
					"root", "123456");
			if (con != null) {
				System.out.println("数据库连接成功！");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) {
		if (con != null) {
			PrintWriter pw = null;
			try {
				String sql = "select u.user_name from  edaily.users u";
				PreparedStatement ps = con.prepareStatement(sql);
				ResultSet rs = ps.executeQuery();

				pw = response.getWriter();
				while (rs.next()) {
					pw.println("<h1>" + rs.getString(1) + "<h1>");
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				pw.flush();
				pw.close();
			}
		} else {
			System.out.println("数据库连接为空！");
		}
	}
}
